#include "types.h"
#include "stat.h"
#include "user.h"
#include "boundedbuffer.h"
#include "param.h"

struct semaphore* lock;
struct BB* bb;

void* 
run()
{  
  int element = thread_getid();
  while(1){
    if(element % 2 ==0){
    //printf(1,"run1=> thread = %d, count = %d\n",element,bb->count);
      semaphore_put(bb,&element);
    //printf(1,"run2=> thread = %d, count = %d\n",element,bb->count);
    }
    else{
    //printf(1,"run1=> thread = %d, count = %d\n",element,bb->count);
      semaphore_pop(bb);
    //printf(1,"run2=> thread = %d, count = %d\n",element,bb->count);
    }
  }
  
  thread_exit(0);
  return 0;
}  

void
threadTest(int n)
{
  int i;
  int threads [NPROC];
  char* stacks [NPROC];
  void** ret = 0;
  
  for(i=0; i<n; i++){
    if ((stacks[i] = (char*) malloc(KSTACKSIZE)) == 0){
      printf(1, "malloc\n");
      return;
    }
    threads[i] = thread_create(&run,(void*)stacks[i], KSTACKSIZE);
  }
  
  for(i=0; i<n; i++){
    if(thread_join(threads[i],ret) == -1)
      printf(1, "thread_join\n");
      
    free(stacks[i]);
  }
  exit();
}

int
main(int argc, char** argv)
{
  int n;
  if(argc<2){
    printf(1,"Usage: %s positive integer (buffer size)\n",argv[0]);
    exit();
  }
  n = atoi(argv[1]);
  
  bb = BB_create(300);
    
  threadTest(n);
  exit();
}
